// 班级管理相关API接口
import { mockClassList, mockApplications } from '@/mock/classData'

// API基础URL（实际项目中应该从环境变量获取）
const API_BASE_URL = import.meta.env.VITE_API_BASE_URL || 'http://localhost:3000/api'

// 获取班级列表
export const getClassList = async (params = {}) => {
  try {
    // 模拟API调用延迟
    await new Promise(resolve => setTimeout(resolve, 300))
    
    // 返回mock数据
    return {
      success: true,
      data: mockClassList,
      total: mockClassList.length,
      message: '获取班级列表成功'
    }
  } catch (error) {
    console.error('获取班级列表失败:', error)
    return {
      success: false,
      data: [],
      total: 0,
      message: '获取班级列表失败'
    }
  }
}

// 创建班级
export const createClass = async (classData) => {
  try {
    await new Promise(resolve => setTimeout(resolve, 500))
    
    const newClass = {
      id: Date.now(),
      ...classData,
      createdAt: new Date().toISOString(),
      status: 'active'
    }
    
    // 在实际项目中，这里应该调用真实的API
    mockClassList.push(newClass)
    
    return {
      success: true,
      data: newClass,
      message: '创建班级成功'
    }
  } catch (error) {
    console.error('创建班级失败:', error)
    return {
      success: false,
      data: null,
      message: '创建班级失败'
    }
  }
}

// 更新班级信息
export const updateClass = async (classId, updateData) => {
  try {
    await new Promise(resolve => setTimeout(resolve, 400))
    
    const classIndex = mockClassList.findIndex(c => c.id === classId)
    if (classIndex === -1) {
      throw new Error('班级不存在')
    }
    
    mockClassList[classIndex] = {
      ...mockClassList[classIndex],
      ...updateData,
      updatedAt: new Date().toISOString()
    }
    
    return {
      success: true,
      data: mockClassList[classIndex],
      message: '更新班级成功'
    }
  } catch (error) {
    console.error('更新班级失败:', error)
    return {
      success: false,
      data: null,
      message: '更新班级失败'
    }
  }
}

// 删除班级
export const deleteClass = async (classId) => {
  try {
    await new Promise(resolve => setTimeout(resolve, 300))
    
    const classIndex = mockClassList.findIndex(c => c.id === classId)
    if (classIndex === -1) {
      throw new Error('班级不存在')
    }
    
    mockClassList.splice(classIndex, 1)
    
    return {
      success: true,
      message: '删除班级成功'
    }
  } catch (error) {
    console.error('删除班级失败:', error)
    return {
      success: false,
      message: '删除班级失败'
    }
  }
}

// 获取班级详情
export const getClassDetail = async (classId) => {
  try {
    await new Promise(resolve => setTimeout(resolve, 200))
    
    const classInfo = mockClassList.find(c => c.id === Number(classId))
    if (!classInfo) {
      throw new Error('班级不存在')
    }
    
    return {
      success: true,
      data: classInfo,
      message: '获取班级详情成功'
    }
  } catch (error) {
    console.error('获取班级详情失败:', error)
    return {
      success: false,
      data: null,
      message: '获取班级详情失败'
    }
  }
}

// 获取用户的班级ID
export const getUserClassId = async (userId) => {
  try {
    const url = `http://127.0.0.1:9001/user/class/id?userId=${userId}`
    const response = await fetch(url, {
      method: 'GET',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${localStorage.getItem('userToken') || ''}`
      }
    })
    
    const result = await response.json()
    
    if (result.code === 200) {
      return {
        success: true,
        data: result.data,
        message: result.message || '获取班级ID成功'
      }
    } else {
      return {
        success: false,
        data: null,
        message: result.message || '获取班级ID失败'
      }
    }
  } catch (error) {
    console.error('获取班级ID失败:', error)
    return {
      success: false,
      data: null,
      message: error.message || '获取班级ID失败'
    }
  }
}

// 学生申请加入班级
export const joinClass = async (joinData) => {
  try {
    const userId = localStorage.getItem('userId') || '1' // 从localStorage获取用户ID，默认为1
    
    // 通过班级ID申请加入
    const url = `http://127.0.0.1:9001/user/join-class`
    const params = new URLSearchParams({
      userId: userId,
      classId: joinData.classId
    })
    
    const response = await fetch(`${url}?${params}`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${localStorage.getItem('userToken') || ''}`
      }
    })
    
    const result = await response.json()
    
    if (result.code === 200) {
      return {
        success: true,
        data: result.data,
        message: result.message || '申请提交成功，等待老师审核'
      }
    } else if (result.code === 400) {
      // 显示错误原因
      return {
        success: false,
        data: null,
        message: result.data?.message || result.message || '申请失败'
      }
    } else if (result.code === 500) {
      // 申请失败
      return {
        success: false,
        data: null,
        message: '申请失败'
      }
    } else {
      return {
        success: false,
        data: null,
        message: result.message || '申请提交失败'
      }
    }
  } catch (error) {
    console.error('申请加入班级失败:', error)
    return {
      success: false,
      data: null,
      message: error.message || '申请提交失败'
    }
  }
}

// 获取学生的班级列表
export const getStudentClasses = async (studentId) => {
  try {
    await new Promise(resolve => setTimeout(resolve, 300))
    
    // 模拟学生已加入的班级
    const studentClasses = mockClassList.filter(c => 
      c.id === 1 || c.id === 2 || c.id === 3
    )
    
    return {
      success: true,
      data: studentClasses,
      message: '获取学生班级列表成功'
    }
  } catch (error) {
    console.error('获取学生班级列表失败:', error)
    return {
      success: false,
      data: [],
      message: '获取学生班级列表失败'
    }
  }
}

// 获取学生的申请记录
export const getStudentApplications = async (studentId) => {
  try {
    await new Promise(resolve => setTimeout(resolve, 300))
    
    // 模拟学生的申请记录
    const studentApplications = mockApplications.filter(a => 
      a.studentId === studentId || a.studentId === 'student123'
    )
    
    return {
      success: true,
      data: studentApplications,
      message: '获取申请记录成功'
    }
  } catch (error) {
    console.error('获取申请记录失败:', error)
    return {
      success: false,
      data: [],
      message: '获取申请记录失败'
    }
  }
}

// 导出班级数据
export const exportClassData = async (classId) => {
  try {
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    return {
      success: true,
      data: {
        downloadUrl: `${API_BASE_URL}/classes/${classId}/export`,
        filename: `class_${classId}_${new Date().toISOString().split('T')[0]}.xlsx`
      },
      message: '导出成功'
    }
  } catch (error) {
    console.error('导出班级数据失败:', error)
    return {
      success: false,
      data: null,
      message: '导出失败'
    }
  }
}
